package 极客算法训练营.chapter03;

/**
 * 给定一个链表，两两交换其中相邻的节点，并返回交换后的链表。
 * <p>
 * 你不能只是单纯的改变节点内部的值，而是需要实际的进行节点交换
 * <p>
 * 示例 1
 * <p>
 * 输入：head = [1,2,3,4]
 * 输出：[2,1,4,3]
 */
public class 两两交换链表中的节点 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        ListNode node = swapPairs(node1);
        System.out.println(node.val + "_" + node.next.val);

    }

    public static ListNode swapPairs(ListNode head) {
        //边界条件
        if (head == null || head.next == null) {
            return head;
        }
        //创建新节点，用来指向结果头指针
        ListNode newNode = new ListNode(0);
        newNode.next = head;
        //tmp为移动指针，每次移动两个单位，L、R为需要交换的两个结点
        ListNode tmp = newNode, L = null, R = null;
        while (tmp.next != null && tmp.next.next != null) {
            L = tmp.next;
            R = tmp.next.next;
            //进行交换
            L.next = R.next;
            tmp.next = R;
            R.next = L;
            //注意交换后为tmp->R->L，tmp指向左结点才是移动两个单位
            tmp = L;
        }
        return newNode.next;
    }

/*    public static ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode L = null, R = null, next = null;
        int index = 0;
        while (head != null || head.next != null) {
            L = head;
            R = head.next;
            next = R.next;
            if (index % 2 == 0) {
                L.next = next;
                R.next = L;
                if (index == 0) head = R;
                R = next;
                index++;
            } else {
                if (R == null || R.next == null) break;
                L = R;
                R = R.next;
            }
        }
        return head;
    }*/
}
